package mlp.game.shadownbolts;

import com.playtomic.android.api.Playtomic;
import com.playtomic.android.api.PlaytomicLeaderboards;
import com.playtomic.android.api.PlaytomicRequestListener;
import com.playtomic.android.api.PlaytomicResponse;
import com.playtomic.android.api.PlaytomicScore;
import com.playtomic.android.api.PlaytomicScoreBoardView;

import mlp.game.shadownbolts.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity extends Activity implements GameOverListener{
	public static final String SETTINGS = "mpl.shadowbolts";
    private RenderView renderView;

    int points = 0;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((RelativeLayout)findViewById(R.id.layoutScore)).setVisibility(View.GONE);
		renderView = (RenderView) findViewById(R.id.gameView);
		renderView.setGameOverListener(this);
		Playtomic.Log().playerLevelStart("Normal");
    }
    
    @Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus == false && renderView.initialized) {
			renderView.pauseGame();
		}
		if (hasFocus == true && renderView.initialized) {
			renderView.drawFrame();
		}
	}
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(renderView.onKeyDown(keyCode, event)){
    		return true;
    	} else {
    		return super.onKeyDown(keyCode, event);
    	}
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	if(renderView.onKeyUp(keyCode, event)){
    		return true;
    	} else {
    		return super.onKeyUp(keyCode, event);
    	}
    }
    
    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (renderView.gameRunning) {
			if (renderView.gamePaused)
				renderView.resumeGame();
			else
				renderView.pauseGame();
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onBackPressed() {
		if (renderView.gameRunning) {
			renderView.pauseGame();
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(R.string.quit_dialog_title)
					.setMessage(R.string.quit_dialog_message)
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									Playtomic.Log().playerLevelQuit("Normal");
									finish();
								}
							}).setNegativeButton(android.R.string.no, null)
					.show();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void gameOver(final long timeAlive, final int shadowbolts) {
		runOnUiThread(new Runnable() {			
			@Override
			public void run() {
				Playtomic.Log().playerLevelWin("Normal");
				points = (int) (timeAlive + 100 * shadowbolts);
				
				final View flashOver = findViewById(R.id.flashOver);
			     
			    AlphaAnimation a2 = new AlphaAnimation(1, 0);
			    a2.setFillBefore(true);
			    a2.setFillAfter(true);
			    a2.setDuration(1500);
			    a2.setRepeatCount(0);
			    flashOver.startAnimation(a2);
				
				CharSequence rank = "";
				if(shadowbolts < 8){
					rank = getResources().getTextArray(R.array.rank)[shadowbolts];
				}else{
					rank = getResources().getTextArray(R.array.rank)[8];
				}				
				String scoreText = getString(R.string.final_score, timeAlive, shadowbolts, points, rank);
				
				((RelativeLayout)findViewById(R.id.layoutScore)).setVisibility(View.VISIBLE);
				((TextView)findViewById(R.id.txt_scoreboard)).setText(scoreText);	
				((ImageView)findViewById(R.id.imageGameLogo)).setVisibility(View.GONE);	
				((TextView)findViewById(R.id.txt_scoreboard)).setVisibility(View.VISIBLE);	
				((Button)findViewById(R.id.btnSubmit)).setVisibility(View.VISIBLE);	
				((PlaytomicScoreBoardView)findViewById(R.id.listScore)).setVisibility(View.VISIBLE);		
				renderView.setVisibility(View.GONE);
				
				((Button)findViewById(R.id.btnStart)).setText("Restart");
				((Button)findViewById(R.id.btnStart)).setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						Playtomic.Log().playerLevelRetry("Normal");
						Intent i = getIntent();
						i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						overridePendingTransition(0, 0);
						finish();
						overridePendingTransition(0, 0);
						startActivity(i);						
					}
				});				
				
				// Look up, your Help button now exits the game
				((Button)findViewById(R.id.btnHelp)).setText("Quit");
				((Button)findViewById(R.id.btnHelp)).setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						finish();					
					}
				});
				
			     final View flashUnder = findViewById(R.id.flashUnder);
			     
			     AlphaAnimation a1 = new AlphaAnimation(0, 1);
			     a1.setDuration(100);
			     a1.setRepeatCount(0);
			     a1.setRepeatMode(AlphaAnimation.REVERSE);
			     a1.setStartOffset((long) (1000 + Math.random() * 1000));
			     a1.setAnimationListener(new AnimationListener() {			
					@Override
					public void onAnimationStart(Animation animation) {}			
					@Override
					public void onAnimationRepeat(Animation animation) {}			
					@Override
					public void onAnimationEnd(Animation animation) {
						animation.setStartOffset((long) (Math.random() * 8000));		
						flashUnder.startAnimation(animation);
					}
			     });
			     flashUnder.startAnimation(a1);
			     
			}
		});	
	}

	
	public void onSubmitClick(View view){
		requestScoreSubmit(points);	
	}
	
	public void onExtraClick(View view) {
		Intent i = null;
		switch (view.getId()) {
		case R.id.btnDonate:
			i = new Intent(Intent.ACTION_VIEW, Uri.parse(IntroActivity.URL_PAYPAL));
			break;
		case R.id.btnFacebook:
			i = new Intent(Intent.ACTION_VIEW, Uri.parse(IntroActivity.URL_FACEBOOK));
			break;
		case R.id.btnTwitter:
			i = new Intent(Intent.ACTION_VIEW, Uri.parse(IntroActivity.URL_TWITTER));
			break;
		default:
			break;
		}
		if(i != null)
			startActivity(i);
	}	
	
	private void requestScoreSubmit(final int points){
		final SharedPreferences sharedPreferences = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
//		if(sharedPreferences.getBoolean("submit_score", true) == false)
//			return;
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(GameActivity.this);
		final EditText editText = new EditText(this);
		editText.setHint("Enter your name");
		editText.setText(sharedPreferences.getString("last_score_name", ""));
		dialog.setCancelable(false);
		dialog.setView(editText);
		dialog.setTitle("Submit score?");
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setMessage("Do you want to submit your score of " + points + " points?");
		dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String name = editText.getText().toString();
				if(name.length() <= 0){
					Toast.makeText(GameActivity.this, "Please enter a name", Toast.LENGTH_SHORT).show();
					requestScoreSubmit(points);
				} else {
					PlaytomicScore score = new PlaytomicScore(name, points);
					leaderBoardSave(score);
					Editor editor = sharedPreferences.edit();
					editor.putString("last_score_name", name);
					editor.commit();
					dialog.dismiss();
				}								
			}
		});
		dialog.setNegativeButton(android.R.string.no, null);
//		dialog.setNegativeButton("Never", new DialogInterface.OnClickListener() {			
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				Editor editor = sharedPreferences.edit();
//				editor.putBoolean("submit_score", false);
//				editor.commit();
//				dialog.dismiss();								
//			}
//		});
		dialog.show();
	}
	
	private void leaderBoardSave(PlaytomicScore score) {
		PlaytomicLeaderboards leaderboards = new PlaytomicLeaderboards();

	    // we need to set a listener
	    leaderboards.setRequestListener(new PlaytomicRequestListener<PlaytomicScore>() {
	        public void onRequestFinished(PlaytomicResponse<PlaytomicScore> playtomicResponse) {
	            if(playtomicResponse.getSuccess()) {
	                // we call a function for successed cases
					Toast.makeText(GameActivity.this, "Your score was submited", Toast.LENGTH_SHORT).show();
					((Button)findViewById(R.id.btnSubmit)).setEnabled(false);
					((PlaytomicScoreBoardView)findViewById(R.id.listScore)).reloadData();
	            }            
	            else {
	                // we call a function for failed cases 
	                //
	                requestLeaderBoardListFailed(playtomicResponse.getErrorCode(), 
	                                                playtomicResponse.getErrorMessage());
	            }
	        }
	    });    
	    
	    leaderboards.save("High scores", score, true, false);
	}
	
//	private void requestLeaderBoardListFinished(final ArrayList<PlaytomicScore> data) {
//	   	runOnUiThread(new Runnable() {			
//			@Override
//			public void run() {
//				((Button)findViewById(R.id.btnSubmit)).setEnabled(false);
//				((PlaytomicScoreBoardView)findViewById(R.id.listScore)).setData(data);
//			}
//		});
//	}

	private void requestLeaderBoardListFailed(int errorCode, String message) {
		Toast.makeText(this, "Error submitting score\nError: " + message + " (" + errorCode + ")", Toast.LENGTH_LONG).show();
		((Button)findViewById(R.id.btnSubmit)).setEnabled(false);
		Log.i("Leaderboard", "Leaderboard list failed to list because of errorcode #" + errorCode 
	            +  " - Message:" + message);
	}
}

interface GameOverListener {
	public void gameOver(long gameRunTime, int shadowboltsKilled);
}